<?php
namespace app\common\service;

use think\Model;

class SignService extends BaseService
{
    public function SignSuccess($sid, $uid, $course_id, $type){
        if($type == 'certificate'){
            //二维码核验
            $courseService = new CourseService();
            if(!$courseService->isBuyCourse($sid, $uid, $course_id)){
                return ['status' => 0, 'msg' => '请先购买此课程'];
            }
        }

        //学员信息
        $swhere = [
            'ui.userid' => $uid,
            'ui.sid' => $sid
        ];
        $field = 'u.user_headimgurl,u.user_nickname,s.formal_status';
        $user_info = db('user_integral')
                    ->alias('ui')
                    ->join('user u','u.user_id = ui.userid')
                    ->join('students s','s.id = ui.students_id','left')
                    ->where($swhere)
                    ->field($field)
                    ->find();

        // 查询学员的班级信息 若课程绑定的班级为学员所在的班级,则$is_course_class_status置为1
        $class_ids = db('course_class')->where(['courseid' => $course_id])->column('classid');
        $class_student = db('class_students')->where(['uid' => $uid, 'classid' => ['in', $class_ids]])->find();
        $is_course_class_status = $class_student ? 1 : 0;

        $where['courseid'] = $course_id;
        $where['uid'] = $uid;
        $course_student_info = db('course_students')->where($where)->find();
        if($course_student_info){
            //签到
            $sign_status = db('course_students')->where($where)->value('sign_status');
            if($sign_status == 0){
                $r = db('course_students')->where($where)->update(['sign_status' => 1]);
                if($r === false){
                    return ['status' => 0,'msg' => '请联系管理员处理'];
                }
            }

            if(($course_student_info['formal_status'] == 1 && $course_student_info['ourclass_status'] == 1) || $is_course_class_status){
                //正式学员
                $type = 1;
            } else {
                //旁听学员
                $type = 2;
            }
        } else {

            //旁听学员
            $type = 2;

            //查询学员信息表
            //$student_info = D('Store/Students')->getStudentInfo(array('uid' => $uid,'sid' => STORE_ID));

            //查询course_listening表
//            $course_listening = db('course_listening')->where(['uid' => $uid,'courseid' => $course_id])->find();

            $course_student_data = array();
            $course_student_data['courseid'] = $course_id;
            $course_student_data['uid'] = $uid;
            $course_student_data['sid'] = $sid;
            $course_student_data['sign_status'] = 1;
            $course_student_data['sign_type'] = $type == 'certificate' ? 3 : 1;  //签到类型(1:扫码签到;2:人脸签到;3:二维码核验签到)
            $course_student_data['addtime'] = time();
            $course_student_data['studentsid'] = db('students')->where(['uid' => $uid, 'sid' => $sid])->value('id');

            if($user_info['formal_status'] == 1){
                $course_student_data['formal_status'] = 1;
                $course_student_data['ourclass_status'] = $is_course_class_status;
                //$course_listening存在，则为老学员，试听申请未通过；不存在，则为老学员，未申请
//                $course_student_data['apply_status'] = !empty($course_listening) ? 2 : 3;

            } else {
                $course_student_data['formal_status'] = 0;
                $course_student_data['ourclass_status'] = $is_course_class_status;
                //$course_listening存在，则为会员，试听申请未通过；不存在，则为会员，未申请
//                $course_student_data['apply_status'] = !empty($course_listening) ? 2 : 3;
            }

            // 查询出学员表是否有记录,如果有就是学员，显示学员证
            $student = db('students')->where(array('uid'=>$uid))->find();
            if($student) {
                $formal_status = $student['formal_status'];
                if($formal_status) {
                    //查询课程关联的班级
                    $relate_class_ids = db('course_class')->where(['courseid' => $course_id])->column('classid');
                    $is_own = db('class_students')->where(['sid' => $sid, 'uid' => $uid, 'classid' => ['in',$relate_class_ids]])->find();
                    if($is_own){
                        $type = 1;
                    }
//                    $type = 1;
                    //$course_student_data['formal_status'] = 0;
                    //$course_student_data['ourclass_status'] = 0;
                }
            }



            $res = db('course_students')->insert($course_student_data);

            if($res === false){
                return ['status' => 0,'msg' => '请联系管理员处理'];
            }

        }

        $field = 'cs.*,cr.name as course_name,cr.speaker,cr.schooltime,cr.schoolovertime,cr.origin_courseid,st.name as student_name,st.formal_status as st_formal_status';
        $condition = array();
        $condition['cs.courseid'] = $course_id;
        $condition['cs.uid'] = $uid;

        $info = db('course_students')->alias('cs')
                ->join('course cr','cr.courseid = cs.courseid')
                ->join('students st','st.uid = cs.uid and st.sid = cs.sid')
                ->where($condition)
                ->field($field)
                ->find();
        $info['schooltime'] = !empty($info['schooltime']) ? date('Y-m-d H:i:s',$info['schooltime']) : '';
        $info['schoolovertime'] = !empty($info['schoolovertime']) ? date('H:i:s',$info['schoolovertime']) : '';
        $info['type'] = $type;
        $info['user_headimgurl'] = $user_info['user_headimgurl'];
        $info['user_nickname'] = $user_info['user_nickname'];
        $info['speaker'] = json_decode($info['speaker'], 1);
        $info['is_quote'] = $info['origin_courseid'] ? 1 : 0;

        return ['status' => 1,'data' => ['content' => $info]];
    }


    /**
     * 获取签到课程详情
     * @param $sid
     * @param $course_id
     * @return array
     */
    public function getCourseDetail($sid, $course_id){

        //获取课程基本信息
        if($course_id){
            $course_detail = db('course')->field('name,speaker,pic,schooltime')->where(['courseid' => $course_id, 'sid' => $sid])->find();
        } else {
            $course_detail = db('course')->field('courseid,name,speaker,pic,schooltime')->where(['sid' => $sid, 'schooltime' => ['<', time()]])->order('courseid DESC')->find();
            $course_id = $course_detail['courseid'];
        }
        if(empty($course_detail)){
            return ['status' => 0, 'msg' => '还没有已经开始的课程'];
        }

        $courseService = new CourseService();
        //获取本班正式学员人数
        $formal_count = $courseService->getFormalStudentsCountByCourseid($course_id);

        //获取成功申请试听学员人数
        $listening_count = $courseService->getPassUserCountByCourseid($course_id);

        //实际签到人数
        $fact_count = $courseService->getSignedCountByCourseid($course_id);

        //获取课程已签到本班正式学员人数
        $fact_formal_count = $courseService->getSignedFormalStudentsCountByCourseid($course_id);

        //获取课程申请试听成功的试听学员人数
        $fact_listening_count = $courseService->getSignedListeningStudentsCountByCourseid($course_id);

        $data = [
            'name' => $course_detail['name'],
            'speaker' => json_decode($course_detail['speaker'], 1),
            'pic' => $course_detail['pic'],
            'schooltime' => date('Y/m/d H:i',$course_detail['schooltime']),
            'should_count' => $formal_count + $listening_count,
            'formal_count' => $formal_count,
            'listening_count' => $listening_count,
            'fact_count' => $fact_count,
            'fact_formal_count' => $fact_formal_count,
            'fact_listening_count' => $fact_listening_count,
            'fact_other_count' => $fact_count - $fact_formal_count - $fact_listening_count
        ];

        return ['status' => 1, 'data' => ['content' => $data]];
    }


    /**
     * 获取某个顾问的学员列表
     * @param $sid
     * @param $uid
     * @param $course_id
     * @return array
     */
    public function getCounselorStudentsList($sid, $uid, $course_id){
        if($course_id == 0){
            //查询最近一次的课程
            $course_id = db('course')->where(['sid' => $sid, 'schooltime' => ['<', time()]])->order('addtime DESC')->limit(1)->value('courseid');
        }
        $where = [
            'cs.sid' => $sid,
            'cs.courseid' => $course_id,
//            'cs.formal_status' => 1,
//            'cs.ourclass_status' => 1,
            'ui.counselor_id' => $uid
        ];

        $list = db('course_students cs')
                ->field('u.user_nickname,u.user_headimgurl,s.name,cs.sign_status,cs.ourclass_status')
                ->join('students s', 's.uid=cs.uid')
                ->join('user_integral ui', 'ui.userid=cs.uid')
                ->join('user u', 'u.user_id=cs.uid')
                ->where($where)
                ->order('cs.addtime DESC')
                ->select();

        return ['status' => 1, 'data' => ['content' => $list]];
    }


    /**
     * 获取签到课程列表
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getSignCourseList($sid, $p, $pageSize){
        $where = [
            'sid' => $sid,
            'schooltime' => ['<', time()]
        ];
        $course_list = db('course')
                        ->field('courseid,name,speaker,pic,schooltime,schoolovertime')
                        ->where($where)
                        ->limit(($p - 1)*$pageSize, $pageSize)
                        ->order('courseid DESC')
                        ->select();

        $course_count = db('course')->where($where)->count();

        $courseService = new CourseService();
        $list = [];

        if($course_list){
            foreach($course_list as $k => $v){
                //获取本班正式学员人数
                $formal_count = $courseService->getFormalStudentsCountByCourseid($v['courseid']);

                //获取成功申请试听学员人数
                $listening_count = $courseService->getPassUserCountByCourseid($v['courseid']);

                //实际签到人数
                $fact_count = $courseService->getSignedCountByCourseid($v['courseid']);

                //学员签到率
                //获取本班正式学员已签到人数
                $formal_signed_count = $courseService->getSignedFormalStudentsCountByCourseid($v['courseid']);
                if($formal_count == 0 || $formal_signed_count == 0){
                    $sign_rate = 0;
                } else {
                    $sign_rate = round($formal_signed_count/$formal_count, 2) * 100;
                }

                $list[$k] = [
                    'courseid' => $v['courseid'],
                    'name' => $v['name'],
                    'speaker' => json_decode($v['speaker'], 1),
                    'pic' => $v['pic'],
                    'schooltime' => date('Y/m/d H:i',$v['schooltime']),
                    'should_count' => $formal_count + $listening_count,
                    'formal_count' => $formal_count,
                    'listening_count' => $listening_count,
                    'fact_count' => $fact_count,
                    'course_status' => $v['schoolovertime'] < time() ? 2 : 1,
                    'sign_rate' => $sign_rate
                ];
            }
        }

        $data = [
            'content' => $list,
            'page' => ['count' => $course_count]
        ];

        return $data;
    }


    /**
     * 获取最近7次课程签到率
     * @param $sid
     * @return array
     */
    public function getLatestSignedCourse($sid){
        $where = [
            'sid' => $sid,
            'schooltime' => ['<', time()]
        ];
        $course_list = db('course')
                        ->field('courseid,name,speaker,schooltime,schoolovertime')
                        ->where($where)
                        ->limit(7)
                        ->order('courseid DESC')
                        ->select();

        $courseService = new CourseService();
        $data = [];

        if($course_list){
            foreach($course_list as $k => $v){
                //获取本班正式学员人数
                $formal_count = $courseService->getFormalStudentsCountByCourseid($v['courseid']);

                //学员签到率
                //获取本班正式学员已签到人数
                $formal_signed_count = $courseService->getSignedFormalStudentsCountByCourseid($v['courseid']);
                if($formal_count == 0 || $formal_signed_count == 0){
                    $formal_sign_rate = 0;
                } else {
                    $formal_sign_rate = round($formal_signed_count/$formal_count, 2) * 100;
                }

                //获取成功申请试听学员人数
                $listening_count = $courseService->getPassUserCountByCourseid($v['courseid']);

                //实际签到人数
                $fact_count = $courseService->getSignedCountByCourseid($v['courseid']);
                //应签人数
                $should_count = $formal_count + $listening_count;
                //总签到率
                if($fact_count == 0 || $should_count == 0){
                    $total_sign_rate = 0;
                } else {
                   $total_sign_rate = round($fact_count/$should_count, 2) * 100;
                }

                $data[$k]['name'] = $v['name'];
                $data[$k]['formal_sign_rate'] = $formal_sign_rate;
                $data[$k]['total_sign_rate'] = $total_sign_rate;
            }
        }
        return $data;
    }

    /**
     * 获取月签到
     * @param $sid
     * @param $os_id
     * @return array
     */
    public function getMonthSigned($sid,$os_id){
        $month_where = [
            'sid' => $sid,
            'os_id' => $os_id
        ];
        $info = db('statis_month_sign')->where($month_where)->find();
        if(empty($info)){
            return ['status' => 0,'msg'=>'参数错误'];
        }
        $where = [
            'scs.sid' => $sid,
            'scs.os_month' => $info['os_month']
        ];
        $list = db('statis_course_sign')->alias('scs')->join('course c','c.courseid = scs.courseid')->where($where)->field('scs.*,c.name')->select();

        if(!empty($list)){
            foreach($list as $k => $v){
                $sign_num = intval($v['sign_ourclass_num']+$v['sign_apply_num']);
                if($sign_num > 0){
                    $new_list[$k]['total_sign'] = (intval($v['signed_ourclass_num']+$v['signed_other_num'])/$sign_num)*100;
                }else{
                    $new_list[$k]['total_sign'] = 0;
                }
                if(intval($v['sign_ourclass_num']) >0){
                    $new_list[$k]['student_sign'] = (intval($v['signed_ourclass_num'])/intval($v['sign_ourclass_num']))*100;
                }else{
                    $new_list[$k]['student_sign'] = 0;
                }

                $new_list[$k]['course_name'] = $v['name'];
            }

        }else{
            $new_list = [];
        }
        $month_string = substr($info['os_month'],4).'/'.substr($info['os_month'],0,4);
        $info['month_string'] = $month_string;
        $info['sign_num'] = $info['sign_ourclass_num']+$info['sign_apply_num'];
        $info['signed_num'] = $info['signed_ourclass_num']+$info['signed_other_num'];
        $info['list'] = $new_list;
        return ['status' => 1,'data' => ['content' => $info]];
    }

    /**
     * 获取月份
     * @param $sid
     * @return array
     */
    public function getMonth($sid){
        $where = [
            'sid' => $sid
        ];
        $list = db('statis_month_sign')->where($where)->order('os_month desc')->field('os_id,os_month')->limit(6)->select();
        if(!empty($list)){
            foreach($list as $k => $v){
                $list[$k]['month_str'] = substr($v['os_month'],0,4).'年'.substr($v['os_month'],4).'月';
            }
        }
        return ['status' => 1,'data' => ['content' => $list]];
    }
}